package com.example.edu.Controller;

import com.example.edu.Dto.*;
import com.example.edu.Entity.History;
import com.example.edu.Service.AIService;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

import static com.example.edu.Utils.MyConstants.SSE_TIMEOUT;

@RestController
@RequestMapping("/ai")
public class AIController {
    @Resource
    AIService aiService;
    private static final Logger logger = LoggerFactory.getLogger(AIController.class);

    @PostMapping("/historyList")
    public Return historyList(HttpServletRequest request){
        return aiService.historyList(request);
    }

    @PostMapping("/historyListM")
    public Return historyListM(HttpServletRequest request){
        return aiService.historyListM(request);
    }

    @PostMapping("/update")
    public Return update(@RequestBody History history){
        return aiService.update(history);
    }

    @PostMapping("/delete")
    public Return delete(@RequestBody History historyId){
        return aiService.delete(historyId.getHistory_id());
    }

    @PostMapping("/chat")
    public SseEmitter chat(@RequestBody AIChatDtoG aiChatData, HttpServletRequest request) {
        SseEmitter emitter = new SseEmitter(SSE_TIMEOUT);

        emitter.onTimeout(() -> {
            logger.warn("SSE Timeout, closing emitter");
            emitter.complete();
        });

        emitter.onCompletion(() -> logger.info("SSE Completed"));

        aiService.chat(aiChatData, request)
                .subscribeOn(Schedulers.io()) // 切换到 IO 线程池
                .subscribe(
                        content -> {
                            try {
                                emitter.send(new AIChatDtoR(content));
                            } catch (IOException e) {
                                logger.error("Error sending SSE message: " + e.getMessage());
                                emitter.completeWithError(e);
                            }
                        },
                        throwable -> {
                            logger.error("Error in SSE streaming: " + throwable.getMessage());
                            emitter.completeWithError(throwable);
                        },
                        () -> {
                            logger.info("All content streamed successfully.");
                            emitter.complete();
                        }
                );
        return emitter;
    }

    @PostMapping("/addRecord")
    public Return addRecord(@RequestBody AddRecordDtoG records) {
        return aiService.addRecord(records);
    }

    @PostMapping("/addHistory")
    public Return addHistory(HttpServletRequest request,@RequestBody History history){
        return aiService.addHistory(request,history);
    }

    @PostMapping("/chatList")
    public Return chatList(@RequestBody ChatListDtoG chatListData){
        return aiService.chatList(chatListData);
    }
}
